package com.haohuo.sort;

import java.util.Arrays;

/**
 * 冒泡排序
 * note：
 * <p>
 * author: Caozhitong
 **/
public class BubbleSort {

    public static void main(String[] args) {

        int[] elements = new int[]{1211,212,31,422,5222,216,712,72,733,232,453,243,233,232};
        sort2(elements);
    }

    public static void sort(int[] elements) {
        int len = elements.length;
        boolean isSwapped;
        do {
            isSwapped = false;
            for (int i = 1; i < len; i++) {
                if (elements[i-1] < elements[i]) {
                    int temp = elements[i];
                    elements[i] = elements[i-1];
                    elements[i-1] = temp;
                    isSwapped = true;
                }
            }
            len--;
        } while (isSwapped);
    }
    public static void sort1(int[] elements) {
        int len = elements.length;
        while (len > 1) {
            for (int i = 1; i < len; i++) {
                if (elements[i-1] < elements[i]) {
                    int temp = elements[i];
                    elements[i] = elements[i-1];
                    elements[i-1] = temp;
                }
            }
            len--;
        }
    }

    public static void sort2(int[] elements) {
        int len = elements.length;
        int lastSwapIndex = elements.length - 1;
        boolean isSwapped;

        int count = 0;
        do {
            System.out.println("第" +  count++ + "趟");
            isSwapped = false;
            for (int i = 1; i < len; i++) {
                if (elements[i-1] < elements[i]) {
                    int temp = elements[i];
                    elements[i] = elements[i-1];
                    elements[i-1] = temp;
                    isSwapped = true;
                    lastSwapIndex = i;
                }
                Arrays.stream(elements).forEach(element -> System.out.print(element + ","));
                System.out.println();
            }
            len = lastSwapIndex;
        } while (isSwapped);
    }

}
